package chapter3;

import java.util.concurrent.atomic.LongAccumulator;

/**
 * @author caiya
 * @date 2020/3/24 22:32
 */
public class LongAccumulatorTest {

    static LongAccumulator longAccumulator = new LongAccumulator((left, right) -> {
        return left + right;
    }, 0);

    static long[] data1 = {0,1,2,3,4,6,0,3434,0,23,1,0};
    static long[] data2 = {0,1,0,3,4,6,0,0,0,23,1,0};

    public static void main(String[] args) throws InterruptedException {
        /**
         * LongAccumulator 和 LongAdder 的区别：
         *      1）LongAccumulator 可以指定累加规则，比如不使用累加，而使用累积
         *      2）LongAccumulator 可以提供累加器初始非零值
         *      3）LongAdder 本质还是基于 LongAccumulator 实现
         */
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (long data: data1) {
                    if (data == 0) {
                        longAccumulator.accumulate(1);
                    }
                }
            }
        });

        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (long data: data2) {
                    if (data == 0) {
                        longAccumulator.accumulate(1);
                    }
                }
            }
        });

        thread.start();
        thread1.start();

        thread.join();
        thread1.join();

        System.out.println("总计:" + longAccumulator.get());
    }
}
